<?php

class Sys_Extensions
{
	function __construct() {
		$this->db = Zend_Registry::get("db");
	}

    function FormatArray($array)
	{
		if(is_array($array))
		{
			echo "<pre>";
			print_r($array);
			echo "<pre>";
		}else{
			echo "Not an array.";
		}
	}
	
	function TurnMsgToObj($post_str)
	{
		if(!empty($post_str))
		{
			$result = simplexml_load_string($post_str, 'SimpleXMLElement', LIBXML_NOCDATA);
		}else{
			$result = NULL;
		}
		
		return $result;
	}
	
	function SendVcode($cellphone)
	{
		//create vcode
		$mod_veri = new Db_Tables_CellphoneVerification();
		$vcode = $mod_veri->AddVcode($cellphone);
		
		//send sms
		$send_result = $this->SendVerifyCode($cellphone, $vcode);
		return $send_result;
	}
	
	function SendVerifyCode($target_num, $verify_code)
	{
		$result = array(
			'result' => 0,
			'reason' => "未知错误"
		);
		
		$mod_params = new Db_Tables_Params();
		$ytx_info = $mod_params->YtxInfo();
		
		$to = $target_num;
		$datas = array($verify_code,'30');
		$tempId = $ytx_info['ytx-phoneVerify-tempId'];
		
		$accountSid = $ytx_info['ytx-accountSid'];
		$accountToken = $ytx_info['ytx-accountToken'];
		$appId = $ytx_info['ytx-appId'];
		$serverIP = 'app.cloopen.com';
		$serverPort = '8883';
		$softVersion = '2013-12-26';
		
		// 初始化REST SDK
		$rest = new Sys_SmsYtx($serverIP,$serverPort,$softVersion);
		$rest->setAccount($accountSid,$accountToken);
		$rest->setAppId($appId);

		// 发送模板短信
		$sms_result = $rest->sendTemplateSMS($to,$datas,$tempId);
		if($sms_result == NULL ) {
			$result['reason'] = "调用接口失败";
		}
		if($sms_result->statusCode!=0) {
			$result['reason'] = "Error:(".$sms_result->statusCode.")".$sms_result->statusMsg;
			//TODO 添加错误处理逻辑
		}else{
			$result = array(
				'result' => 1,
				'reason' => "发送成功"
			);
		}
	
		return $result;
	}
	
	function SendAgentNotice($target_num_arr, $url, $agent_name, $account_name, $pwd)
	{
		$result = array(
			'result' => 0,
			'reason' => "未知错误"
		);
		
		$mod_params = new Db_Tables_Params();
		$ytx_info = $mod_params->YtxInfo();
		
		$datas = array($agent_name, $url, $account_name, $pwd);
		$tempId = $ytx_info['ytx-agent-notice-tempId'];
		
		$accountSid = $ytx_info['ytx-accountSid'];
		$accountToken = $ytx_info['ytx-accountToken'];
		$appId = $ytx_info['ytx-appId'];
		$serverIP = 'app.cloopen.com';
		$serverPort = '8883';
		$softVersion = '2013-12-26';
		
		// 初始化REST SDK
		$rest = new Sys_SmsYtx($serverIP,$serverPort,$softVersion);
		$rest->setAccount($accountSid,$accountToken);
		$rest->setAppId($appId);

		// 发送模板短信
		foreach($target_num_arr as $to)
		{
			if($to)
			{
				$sms_result = $rest->sendTemplateSMS($to,$datas,$tempId);
				if($sms_result == NULL ) {
					$result['reason'] = "调用接口失败";
				}
				if($sms_result->statusCode!=0) {
					$result['reason'] = "Error:(".$sms_result->statusCode.")".$sms_result->statusMsg;
					//TODO 添加错误处理逻辑
				}else{
					$result = array(
						'result' => 1,
						'reason' => "发送成功"
					);
				}
			}
		}
		
		return $result;
	}
	
	function Broadcast($url, $data_array, $type) //type=1 POST type=2 GET
	{
		$data_str = Zend_Json::encode($data_array);
		
		if(1 == $type)
		{
			$type_txt = "POST";
		}else{
			$type_txt = "GET";
		}
		
		$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type_txt);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		
    	if (curl_errno($ch)) {
    		echo 'Errno'.curl_error($ch);
    	}
    	curl_close($ch);
		
		$result = Zend_Json::decode($tmpInfo);
		
		return $result;
	}
	
	function Broadcast2($url, $data_array, $type) //type=1 POST type=2 GET
	{
		$data_query = http_build_query($data_array);
		$data_len = strlen($data_query);
		
		if(1 == $type)
		{
			$type_txt = "POST";
		}else{
			$type_txt = "GET";
		}
		
		$header = array(
			'Content-Type' => 'application/x-www-form-urlencoded',
			'Accept' => 'application/xml',
			'Content-Length' => 0
		  );
		
		$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type_txt);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		$result = curl_exec($ch);
		
    	if (curl_errno($ch)) {
    		echo 'Errno'.curl_error($ch);
    	}
    	curl_close($ch);
		
		return $result;
	}
	
	function GetIp() {
		if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
			$ip = getenv("HTTP_CLIENT_IP");
		} elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		} elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
			$ip = getenv("REMOTE_ADDR");
		} elseif (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
			$ip = $_SERVER['REMOTE_ADDR'];
		} else {
			$ip = "unknown";
		}
		
		return ($ip);
	}
	
	function NumberFormat($num, $type)
	{
		if(!$num)
		{
			$num = 0;
		}
		
		$result = $num;
		
		if(1 == $type)
		{
			$result = number_format($num, 0, ".", ",");
		}
		
		return $result;
	}
	
	function ReCalculateNewContract($contract_id=NULL)
	{
		$result = FALSE;
		
		if($contract_id)
		{
			$target_session = $_SESSION['contract-edit-type2'][$contract_id];	
		}else{
			$target_session = $_SESSION['contract'];
		}
		
		if($target_session)
		{
			if(!empty($target_session['sku_info']))
			{
				$mod_sku = new Db_Tables2_BSku();
				$start_date = "";
				$expired_date = "";
				$contract_claim_amount = 0;
				$contract_value = 0;
				
				foreach($target_session['sku_info'] as $id => $sku_info)
				{
					if($sku_info['sku_id'])
					{
						$sku_path = $mod_sku->GetSkuPath($sku_info['sku_id']);
						$target_session['sku_info'][$id]['sku_path'] = $sku_path['path_name'];
						
						if(2 == $target_session['contract_info']['contract_type_id']) //免费合同
						{
							$target_session['sku_info'][$id]['unit_price'] = 0;
							$contract_claim_amount += 0;
						}else{
							$sku_row = $mod_sku->GetSkuRow($sku_info['sku_id']);
							$target_session['sku_info'][$id]['unit_price'] = $sku_row['unit_price'];
							
							if(961 == $sku_info['sku_id'])
							{
								$contract_claim_amount += ($sku_row['unit_price'] * $sku_info['sku_quantity']);
							}else{
								$contract_claim_amount += ($sku_row['unit_price'] * $sku_info['sku_quantity'] / 2);
							}
							
						}
						
						$contract_value += $sku_info['actual_pay'];
					}
					
					if($start_date > $sku_info['start_date'] || !$start_date)
					{
						$start_date = $sku_info['start_date'];
					}
					
					if($expired_date > $sku_info['expired_date'] || !$expired_date)
					{
						$expired_date = $sku_info['expired_date'];
					}
				}
				
				$target_session['contract_info']['start_date'] = $start_date;
				$target_session['contract_info']['expired_date'] = $expired_date;
				$target_session['contract_info']['contract_claim_amount'] = $contract_claim_amount;
				$target_session['contract_info']['contract_value'] = $contract_value;
			}else{
				$target_session['contract_info']['start_date'] = NULL;
				$target_session['contract_info']['expired_date'] = NULL;
				$target_session['contract_info']['contract_claim_amount'] = 0;
				$target_session['contract_info']['contract_value'] = 0;
			}
		}
		
		if($contract_id)
		{
			$_SESSION['contract-edit-type2'][$contract_id] = $target_session;	
		}else{
			$_SESSION['contract'] = $target_session;
		}
		
		return $result;
	}
	
	function MakeDealerStringInContract($contract_id=NULL)
	{
		$result = FALSE;
		
		if($contract_id)
		{
			$target_session = $_SESSION['contract-edit-type2'][$contract_id];	
		}else{
			$target_session = $_SESSION['contract'];
		}
		
		if($target_session)
		{
			if(!empty($target_session['contract_info']['dealers_arr']))
			{
				$tmp = array();
				
				foreach($target_session['contract_info']['dealers_arr'] as $dealer_id => $dealer_name)
				{
					$tmp[] = $dealer_id;
				}
				
				$target_session['contract_info']['dealers_str'] = implode(", ", $tmp);
			}else{
				$target_session['contract_info']['dealers_str'] = NULL;
			}
			
			if($contract_id)
			{
				$_SESSION['contract-edit-type2'][$contract_id] = $target_session;	
			}else{
				$_SESSION['contract'] = $target_session;
			}
			
			$result = TRUE;
		}
		
		return $result;
	}
	
	function GenerateOrderSid()
	{
		$arr = array(
			"CONTRACT_SID_DATE",
			"CONTRACT_LAST_SID_NUM",
			"CONTRACT_HEAD"
		);
		
		$mod_params = new Db_Tables2_BDictParams();
		$get_params_num = $mod_params->GetVal($arr);
		
		$pre = $get_params_num['CONTRACT_HEAD'];
		$second = date("Ymd");
		
		$dealers_db = Zend_Registry::get("dealers_db");
		$set = array();
		
		if($second > $get_params_num['CONTRACT_SID_DATE'])
		{
			$last = "01";
			$set['pval'] = $second;
			$where = "pkey='CONTRACT_SID_DATE'";
			$dealers_db->update("b_dict_params", $set, $where);
		}else{
			$last = $get_params_num['CONTRACT_LAST_SID_NUM'];
			$last = intval($last) + 1;
			
			if($last < 10)
			{
				$last = "0".$last;
			}
		}
		
		$set['pval'] = $last;
		$where = "pkey='CONTRACT_LAST_SID_NUM'";
		$dealers_db->update("b_dict_params", $set, $where);
		
		return $pre.$second.$last;
	}
	
	function ExcelColumnHeadGeneration($num)
	{
		$result = array();
		
		$source1 = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
		$source2 = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
		
		if(0 < $num)
		{
			foreach($source1 as $s1)
			{
				if(0 < $num)
				{
					$result[] = $s1;
					$num -= 1;
				}
			}
		}
		
		if(0 < $num)
		{
			foreach($source1 as $s1)
			{
				foreach($source2 as $s2)
				{
					if(0 < $num)
					{
						$result[] = $s1.$s2;
						$num -= 1;
					}
				}
			}
		}
		
		return $result;
	}
	
	function FormatDate($date)
	{
		$result = "";
		
		if($date)
		{
			$d = date("w", mktime(0,0,0,substr($date,5,2),substr($date,8,2),substr($date,0,4)));
			
			switch ($d)
			{
				case 1:
					$result = "星期一";
					break;
				case 2:
					$result = "星期二";
					break;
				case 3:
					$result = "星期三";
					break;
				case 4:
					$result = "星期四";
					break;
				case 5:
					$result = "星期五";
					break;
				case 6:
					$result = "星期六";
					break;
				default:
					$result = "星期日";
					break;
			}
		}
		
		return $result;
	}
	
	function GetProductIds($sess)
	{
		$result = array();
		
		if(!empty($sess))
		{
			foreach($sess as $se)
			{
				if(!in_array($se['product_id'], $result))
				{
					$result[] = $se['product_id'];
				}
			}
		}
		
		return $result;
	}
}